package org.weed.remote.network.server;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class StreamServer implements Runnable {
	private int port;
	private ServerSocket serverSocket;
	private Socket client;
	private boolean isStopped;
	
	public StreamServer(int port) {
		this.port = port;
	}
	
	public void run() {
		isStopped = false;
		try {
			serverSocket = new ServerSocket(port);
			System.err.println("Server starts at port " + port);
			while (!isStopped) {				
				client = serverSocket.accept();
				System.out.println(client.getRemoteSocketAddress() + " connected.");
				connectionHandler(client);
				client.close();
				System.out.println(client.getRemoteSocketAddress() + " disconnected=" + client.isClosed() + ".");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	protected void connectionHandler(Socket client) {
		try {
			BufferedReader input = new BufferedReader(new InputStreamReader(client.getInputStream()));
			BufferedWriter output = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
			String line;
			while ((line = input.readLine()) != null) {
				processLine(line);
			}
		} catch (Exception e) {
			
		}
	}
	
	protected void processLine(String request) {
		System.out.println(request);
	}
	
	public Socket getClient() {
		return client;
	}
	
	public static void main(String[] args) {
		StreamServer server = new StreamServer(80);
		server.run();
	}
}
